<?
##########################################################################
#		DOCUMENTATION
##########################################################################
# Login script. Start the session and handle the cookies. When everything is
# set returns to view.php
#
# © LiberLab group, 2011
##########################################################################

require_once("dataStructure/user.php");
require_once("dynamic/base/sendData.php");

session_start();

class Login extends SendData{
	public function __construct() {
		parent::__construct("login");
	}
	
	public function main(){
		# get some parameters
		$nickname = strtolower(getParam("nickname", ""));
		$password = getParam("password", "");
		$cookie = getParam("cookie_on", 0);
		# build the link from where we came from skipping the values given:
		# example: http://localhost/basidati/public_html/php/view.php?page=login
		$query = $this->queryBuilder(array("password", "nickname", "cookie_on", "no_user", "no_password"));

		if ($nickname and $password){
			$userClass = new User();
			$passwordEncrypted = $userClass->login($nickname, $password);
			# if yes: we logged, set cookies and session
			if ($passwordEncrypted){
				$this->setSession("nickname", $nickname);
				$this->setSession("password", $passwordEncrypted);
				if ($cookie){
					$this->setCookie("nickname", $nickname);
					$this->setCookie("password", $passwordEncrypted);
				}
				# ok done, redirect to home page
				return $this->redirect(str_replace("page=login", "page=index", $query)); 
			}else{
				# uhm, we have some problems: is wrong the password or the nickname?
				$userId = $userClass->getUserId($nickname)->id;
				$this->checkInsert((!$userId), "&no_user=1");
				$this->checkInsert(1, "&no_password=1");
			}
		}else{
			# not enough parameters given
			$this->checkInsert((!$nickname), "&no_user=1");
			$this->checkInsert(1, "&no_password=1");
		}
		# redirect with errors, finalize will clean the query
		return $this->redirect($this->queryFinalize($checkArray, $query)); 
	}

	public function __destruct() {
		parent::__destruct();
	}
};

$login = new Login();
$login->main();

?>
